﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Vasuleg.Logic.Control
{
    public abstract class GameControllerBase : MonoBehaviour
    {
        private readonly List<(KeyCode, Action<KeyCode>)> _keyUpListeningQueue = new();
        private readonly List<(KeyCode, Action<KeyCode>)> _keyDownListeningQueue = new();
        private readonly List<(KeyCode, Action<KeyCode>)> _keyListeningQueue = new();

        private void Update()
        {
            if (!Input.anyKey)
            {
                return;
            }

            TriggerListeningQueue(_keyUpListeningQueue, Input.GetKeyUp);
            TriggerListeningQueue(_keyDownListeningQueue, Input.GetKeyDown);
            TriggerListeningQueue(_keyListeningQueue, Input.GetKey);
        }

        protected void AddKeyListening(KeyCode keyCode, Action<KeyCode> action)
        {
            _keyListeningQueue.Add((keyCode, action));
        }

        protected void RemoveKeyListening(KeyCode keyCode, Action<KeyCode> action)
        {
            _keyListeningQueue.RemoveAll(group => group.Item1 == keyCode && group.Item2 == action);
        }
        
        


        private static void TriggerListeningQueue(List<(KeyCode, Action<KeyCode>)> listeningQueue,
            Func<KeyCode, bool> inputFunc)
        {
            if (listeningQueue.Count <= 0)
            {
                return;
            }

            foreach (var (keyCode, action) in listeningQueue)
            {
                if (inputFunc(keyCode))
                {
                    action(keyCode);
                }
            }
        }
    }
}